package com.hzy.api;

import com.hzy.service.document.DocumentVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 负责处理 /api/documents/* 相关的 API 路由。
 */
public class DocumentApiVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(DocumentApiVerticle.class);

    // 提供一个静态方法来获取此 Verticle 的 Router，供主 HttpServerVerticle 挂载
    public static Router createRouter(Vertx vertx) {
        Router router = Router.router(vertx);

        // 添加文档 API 路由
        router.post("/").handler(context -> { // 注意这里是 "/" 因为它将被挂载到 "/api/documents"
            JsonObject document = context.body().asJsonObject();
            if (document == null || !document.containsKey("title") || !document.containsKey("content")) {
                context.response()
                        .setStatusCode(400)
                        .end(new JsonObject().put("error", "Bad Request").put("details", "Document must contain 'title' and 'content'.").encodePrettily());
                return;
            }

            // 通过 Event Bus 请求 DocumentVerticle
            vertx.eventBus().<JsonObject>request(DocumentVerticle.ADD_DOCUMENT_ADDRESS, document)
                    .onSuccess(reply -> {
                        context.response()
                                .setStatusCode(200)
                                .end(reply.body().encodePrettily());
                    })
                    .onFailure(err -> {
                        LOGGER.error("Failed to add document: {}", err.getMessage());
                        context.fail(err);
                    });
        });

        // 根据ID获取文档 API 路由
        router.get("/:id").handler(context -> {
            String docId = context.pathParam("id");
            if (docId == null || docId.isEmpty()) {
                context.response()
                        .setStatusCode(400)

                        .end(new JsonObject().put("error", "Bad Request").put("details", "Document ID cannot be empty.").encodePrettily());
                return;
            }

            // 通过 Event Bus 请求 DocumentVerticle
            vertx.eventBus().<JsonObject>request(DocumentVerticle.GET_DOCUMENT_BY_ID_ADDRESS, docId)
                    .onSuccess(reply -> {
                        context.response()
                                .setStatusCode(200)
                                .end(reply.body().encodePrettily());
                    })
                    .onFailure(err -> {
                        LOGGER.error("Failed to get document by ID {}: {}", docId, err.getMessage());
                        context.fail(err);
                    });
        });
        return router;
    }
}